local UIBase = require("view.UIBase")
local PopupMagicKeyUp = class("PopupMagicKeyUp", UIBase)
local MagicKeyDataHelper = require("data.helper.MagicKeyDataHelper")
local TextHelper = require("utils.TextHelper")
local Vector3 = require("utils.Vector3")
local Color = require("utils.Color")
local UserDataHelper = require("data.helper.UserDataHelper")

function PopupMagicKeyUp:ctor(unit)
    self._unit = unit
    local resource = {
        path = "Prefabs/View/MagicKey",
        name = "PopupMagicKeyUp",
        canvas = 3
    }
    PopupMagicKeyUp.super.ctor(self, resource)
end

function PopupMagicKeyUp:start()
    self._btnUp.onClick:AddListener(handler(self, self._onBtnUPClick))
    self._btnClose.onClick:AddListener(handler(self, self._onBtnCloseCLick))
    self:_updateView()
end

function PopupMagicKeyUp:_removeAttr()
    local count = self._attrRoot.childCount
    for i = 0, count - 1, 1 do
        local child = self._attrRoot:GetChild(i)
        GameUtils.destroy(child.gameObject)
    end
end

function PopupMagicKeyUp:_updateView()
    local config = self._unit:getConfig()
    self._textName.text = config.name
    self._textDesc.text = config.desc
    self._textLevel.text = Lang.get("lang_level_show", {level = self._unit:getLevel()})
    self._imageMagickey.sprite = G_ResourceManager:loadSprite("MagickeyAltas", config.res)
    local costCfg = MagicKeyDataHelper.getMagicKeyUpCost(self._unit)
    self._costIcon:updateUI(costCfg.cost_type1, costCfg.cost_value1)

    local haveNum = UserDataHelper.getNumByTypeValue(costCfg.cost_type1, costCfg.cost_value1)
    self._textCostNum.text = (haveNum .. "/" .. costCfg.cost_size1)
    self:_updateAttr()
end

function PopupMagicKeyUp:_updateAttr()
    local attrs = MagicKeyDataHelper.getMagicKeyAttr(self._unit)
    local index = 1
    self:_removeAttr()
    for id, value in pairs(attrs) do
        local name, value = TextHelper.getAttrBasicText(id, value)
        local text = G_UIUtil.createText(self._attrRoot, Vector3.new(0, index * 26, 0))
        text.text = name .. "+" .. value
        text.fontSize = 24
        text.color = Color.RED_COLOR
        index = index + 1
    end
end

function PopupMagicKeyUp:_onBtnUPClick()
    if not self._unit then
        return
    end
    local ErrorCodeConst = require("const.ErrorCodeConst")
    local ret = G_UserData:getMagickey():upgradeMagickey(self._unit:getId())
    if ret == ErrorCodeConst.OK then
        self:_updateView()
        G_Prompt:showTip(Lang.get("upgarde_success"))
    else
        G_Prompt:processError(ret)
    end
end

function PopupMagicKeyUp:_onBtnCloseCLick()
    printDebug("PopupMagicKeyUp:_onBtnCloseCLick")
    self:close()
end

return PopupMagicKeyUp
